<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="辅件编号">
              <a-input placeholder="请输入辅件编号" v-model="queryParam.materialCode"></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="辅件名称">
              <a-input placeholder="请输入辅件名称" v-model="queryParam.materialName"></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="规格型号">
              <a-input placeholder="请输入规格型号" v-model="queryParam.specification"></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="状态">
              <j-dict-select-tag placeholder="请选择状态" v-model="queryParam.status" dictCode="wms_material_status"/>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <a-button style="margin-left: 8px" @click="searchReset" icon="reload">重置</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-button type="primary" icon="plus" @click="handleAdd" v-if="hasPermission('wms:material:auxiliary:add')">新增</a-button>
      <a-button type="primary" icon="download" @click="handleExport" v-if="hasPermission('wms:material:auxiliary:export')">导出</a-button>
      <a-upload
        name="file"
        :showUploadList="false"
        :action="uploadUrl"
        :headers="tokenHeader"
        :data="{materialType: '3'}"
        @change="handleImportChange"
        v-if="hasPermission('wms:material:auxiliary:import')">
        <a-button icon="import">导入</a-button>
      </a-upload>
      <a-dropdown v-if="selectedRowKeys.length > 0">
        <a-menu slot="overlay">
          <a-menu-item key="1" @click="batchDel" v-if="hasPermission('wms:material:auxiliary:delete')">
            <a-icon type="delete"/>删除
          </a-menu-item>
        </a-menu>
        <a-button style="margin-left: 8px">
          批量操作
          <a-icon type="down"/>
        </a-button>
      </a-dropdown>
    </div>

    <!-- table区域-begin -->
    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择 <a style="font-weight: 600">{{ selectedRowKeys.length }}</a>项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div>

      <a-table
        ref="table"
        size="middle"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
        @change="handleTableChange">

        <span slot="action" slot-scope="text, record">
          <a @click="handleEdit(record)">编辑</a>
          <a-divider type="vertical" />
          <a-dropdown>
            <a class="ant-dropdown-link">更多 <a-icon type="down" /></a>
            <a-menu slot="overlay">
              <a-menu-item>
                <a @click="handleDetail(record)">查看明细</a>
              </a-menu-item>
              <a-menu-item>
                <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
                  <a>删除</a>
                </a-popconfirm>
              </a-menu-item>
            </a-menu>
          </a-dropdown>
        </span>

        <template slot="statusSlot" slot-scope="text">
          <a-tag :color="text == '0' ? 'green' : 'red'">
            <j-dict-label :value="text" dictCode="wms_material_status"/>
          </a-tag>
        </template>
        
        <template slot="materialImageSlot" slot-scope="text">
          <div v-if="text" class="drawing-thumbnail-container" @click="handlePreview(text)">
            <img
              v-if="isImageFile(text)"
              :src="getImageUrl(text)"
              class="drawing-thumbnail"
              alt="物料图片"
              @error="handleImageError"
            />
            <a-icon v-else type="file-pdf" class="file-icon" />
            <span class="thumbnail-filename">{{ getFileName(text) }}</span>
          </div>
          <span v-else>-</span>
        </template>
      </a-table>
    </div>
    <!-- table区域-end -->

    <!-- 图片预览 -->
    <a-modal :visible="previewVisible" :footer="null" @cancel="previewVisible = false">
      <img alt="物料图片" style="width: 100%" :src="previewImage" />
    </a-modal>

    <!-- 表单区域 -->
    <material-modal ref="modalForm" @ok="modalFormOk"></material-modal>

    <!-- 物料明细 -->
    <material-detail-modal ref="detailModal"></material-detail-modal>
  </a-card>
</template>

<script>
  import MaterialModal from './modules/MaterialModal'
  import MaterialDetailModal from './modules/MaterialDetailModal'
  import { JeecgListMixin } from '@/mixins/JeecgListMixin'
  import JDictSelectTag from '@/components/dict/JDictSelectTag.vue'
  import JDictLabel from '@/components/dict/JDictLabel.vue'
  import { materialList, materialDelete, materialDeleteBatch, materialExport, materialImport } from '@/api/wms'
  import { getAction } from '@/api/manage'
  import { USER_AUTH, SYS_BUTTON_AUTH } from '@/store/mutation-types'
  import Vue from 'vue'
  import { downFile } from '@/api/manage'
  import { getFileAccessHttpUrl } from '@/api/manage'
  
  export default {
    name: 'AuxiliaryList',
    mixins: [JeecgListMixin],
    components: {
      MaterialModal,
      MaterialDetailModal,
      JDictSelectTag,
      JDictLabel
    },
    data() {
      return {
        description: '辅件管理',
        // 查询条件
        queryParam: {
          materialType: '3' // 默认查询辅件类型
        },
        // 表头
        columns: [
          {
            title: '#',
            dataIndex: '',
            key: 'rowIndex',
            width: 60,
            align: 'center',
            customRender: function (t, r, index) {
              return parseInt(index) + 1
            }
          },
          {
            title: '辅件编号',
            align: 'center',
            dataIndex: 'materialCode'
          },
          {
            title: '辅件名称',
            align: 'center',
            dataIndex: 'materialName'
          },
          {
            title: '物料图片',
            align: 'center',
            dataIndex: 'materialImage',
            scopedSlots: { customRender: 'materialImageSlot' }
          },
          {
            title: '规格型号',
            align: 'center',
            dataIndex: 'specification'
          },
          {
            title: '单位',
            align: 'center',
            dataIndex: 'unit'
          },
          {
            title: '单位成本',
            align: 'center',
            dataIndex: 'unitCost',
            customRender: (text) => {
              return text ? '¥' + parseFloat(text).toFixed(2) : '¥0.00';
            }
          },
          {
            title: '预警上限',
            align: 'center',
            dataIndex: 'upperLimit'
          },
          {
            title: '预警下限',
            align: 'center',
            dataIndex: 'lowerLimit'
          },
          {
            title: '品牌',
            align: 'center',
            dataIndex: 'brand'
          },
          {
            title: '颜色',
            align: 'center',
            dataIndex: 'color'
          },
          {
            title: '状态',
            align: 'center',
            dataIndex: 'status',
            scopedSlots: { customRender: 'statusSlot' }
          },
          {
            title: '操作',
            dataIndex: 'action',
            align: 'center',
            scopedSlots: { customRender: 'action' }
          }
        ],
        url: {
          list: "/wms/material/list",
          delete: "/wms/material/delete",
          deleteBatch: "/wms/material/deleteBatch",
          exportXlsUrl: materialExport
        },
        // 上传相关
        uploadUrl: materialImport,
        // 权限相关
        permissionList: [],
        // 预览相关
        previewVisible: false,
        previewImage: ''
      }
    },
    created() {
      // 禁用mixin中的created钩子自动加载数据
      this.disableMixinCreated = true
      
      // 加载字典数据
      this.initDictConfig()
      
      // 页面加载时重置查询条件
      this.searchReset()
      
      // 添加默认的物料类型过滤
      this.queryParam.materialType = '3'
      // 获取权限列表
      this.loadPermissions()
      // 手动加载数据，确保带上materialType参数
      this.loadData()
      setTimeout(() => {
        const wmsPermissions = ['wms:material:auxiliary:add', 'wms:material:auxiliary:edit', 'wms:material:auxiliary:delete', 'wms:material:auxiliary:export']
        wmsPermissions.forEach(perm => {
          console.log(`权限 ${perm} 是否存在:`, this.hasPermission(perm))
        })
      }, 500)
    },
    methods: {
      // 导入回调
      handleImportChange(info) {
        if (info.file.status === 'done') {
          if (info.file.response.success) {
            this.$message.success(info.file.response.message || '导入成功！');
            this.loadData();
          } else {
            this.$message.error(info.file.response.message || '导入失败！');
          }
        } else if (info.file.status === 'error') {
          this.$message.error('导入失败！');
        }
      },
      
      // 获取图片URL
      getImageUrl(text) {
        if (!text) return '';
        try {
          // 使用jeecg标准的文件访问方式
          return getFileAccessHttpUrl(text);
        } catch (error) {
          console.error('获取文件URL失败:', error);
          return '';
        }
      },
      
      // 预览图片
      handlePreview(text) {
        this.previewImage = this.getImageUrl(text);
        this.previewVisible = true;
      },
      
      // 检查是否为图片文件
      isImageFile(url) {
        if (!url) return false;
        return /\.(jpg|jpeg|png|gif|bmp)$/i.test(url);
      },
      
      // 获取文件名
      getFileName(url) {
        if (!url) return '';
        const parts = url.split('/');
        return parts[parts.length - 1];
      },
      
      // 处理图片加载错误
      handleImageError(e) {
        console.error('图片加载失败:', e);
        // 替换为默认的无图片图标
        e.target.style.display = 'none';
        const container = e.target.parentNode;
        if (container) {
          // 添加一个图标表示图片加载失败
          const icon = document.createElement('i');
          icon.className = 'anticon anticon-picture';
          icon.style.fontSize = '24px';
          icon.style.color = '#d9d9d9';
          container.insertBefore(icon, e.target);

          // 添加错误提示文本
          const errorText = document.createElement('div');
          errorText.innerText = '图片不存在';
          errorText.style.color = '#ff4d4f';
          errorText.style.fontSize = '12px';
          errorText.style.marginTop = '4px';
          container.appendChild(errorText);
        }
      },
      
      // 加载权限
      loadPermissions() {
        console.log('开始加载权限列表')
        
        // 从sessionStorage获取权限
        let authList = JSON.parse(sessionStorage.getItem(USER_AUTH) || "[]")
        console.log('从sessionStorage获取的权限列表:', authList)
        
        // 如果sessionStorage中没有权限，尝试从localStorage获取
        if (!authList || authList.length === 0) {
          authList = JSON.parse(localStorage.getItem(USER_AUTH) || "[]")
          console.log('从localStorage获取的权限列表:', authList)
        }
        
        // 从按钮权限中获取
        const buttonAuth = JSON.parse(sessionStorage.getItem(SYS_BUTTON_AUTH) || localStorage.getItem(SYS_BUTTON_AUTH) || "[]")
        console.log('按钮权限列表:', buttonAuth)
        
        // 合并权限
        if (buttonAuth && buttonAuth.length > 0) {
          authList = authList.concat(buttonAuth)
        }
        
        // 临时添加WMS相关权限用于测试
        const testPermissions = [
          {action: 'wms:material:auxiliary:add'},
          {action: 'wms:material:auxiliary:edit'},
          {action: 'wms:material:auxiliary:delete'},
          {action: 'wms:material:auxiliary:export'},
          {action: 'wms:material:auxiliary:import'}
        ]
        authList = authList.concat(testPermissions)
        
        // 提取action字段
        this.permissionList = authList.map(auth => auth.action || auth)
        console.log('最终权限列表:', this.permissionList)
      },
      
      // 判断是否有权限
      hasPermission(permission) {
        if (!permission) return true // 如果未指定权限，默认有权限
        
        console.log('检查权限:', permission)
        console.log('权限列表:', this.permissionList)
        console.log('检查权限列表中是否包含指定权限:', this.permissionList.includes(permission))

        // 检查权限列表中是否包含指定权限
        if (this.permissionList.includes(permission)) {
          return true
        }
        
        // 检查权限列表中是否包含以逗号分隔的多个权限
        for (let perm of this.permissionList) {
          if (perm && perm.includes(',')) {
            const perms = perm.split(',')
            if (perms.includes(permission)) {
              return true
            }
          }
        }
        
        return false
      },
      
      // 导出Excel
      handleExport() {
        if (!this.url.exportXlsUrl) {
          this.$message.error("请设置url.exportXlsUrl属性!")
          return
        }
        
        let params = this.getQueryParams() // 查询条件
        
        // 使用downFile函数导出Excel
        this.loading = true
        downFile(this.url.exportXlsUrl, params).then((data) => {
          if (!data) {
            this.$message.warning("文件下载失败")
            return
          }
          if (typeof window.navigator.msSaveBlob !== 'undefined') {
            window.navigator.msSaveBlob(new Blob([data], {type: 'application/vnd.ms-excel'}), '辅件信息.xls')
          } else {
            let url = window.URL.createObjectURL(new Blob([data], {type: 'application/vnd.ms-excel'}))
            let link = document.createElement('a')
            link.style.display = 'none'
            link.href = url
            link.setAttribute('download', '辅件信息.xls')
            document.body.appendChild(link)
            link.click()
            document.body.removeChild(link) // 下载完成移除元素
            window.URL.revokeObjectURL(url) // 释放掉blob对象
          }
          this.loading = false
        })
      },
      
      handleDetail(record) {
        this.$refs.detailModal.show(record.id, record.materialName)
      },

      handleAdd() {
        this.$refs.modalForm.add('3') // 传入辅件类型
      },

      handleEdit(record) {
        this.$refs.modalForm.edit(record);
      }
    }
  }
</script> 

<style lang="less" scoped>
.drawing-thumbnail-container {
  cursor: pointer;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 4px;
  border: 1px solid transparent;
  border-radius: 4px;
  transition: all 0.3s;

  .drawing-thumbnail {
    max-width: 60px;
    max-height: 40px;
    object-fit: contain;
    border: 1px solid #eee;
  }

  .file-icon {
    font-size: 24px;
    color: #1890ff;
  }

  .thumbnail-filename {
    font-size: 12px;
    color: #666;
    margin-top: 4px;
    max-width: 100%;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    text-align: center;
  }

  &:hover {
    background-color: #f0f7ff;
    border-color: #1890ff;

    .drawing-thumbnail {
      border-color: #1890ff;
    }

    .file-icon {
      color: #40a9ff;
    }

    .thumbnail-filename {
      color: #1890ff;
    }
  }
}
</style> 